import type { UserLoginData } from "@/api/login.ts"
import { loginApi } from "@/api/login.ts"
import { removeToken, setToken } from "@/utils/auth.ts"
import { useTagsViewStore } from "@/stores/tagsView.ts"

export const useLoginStore = defineStore("login", () => {
  const state = reactive({
    token: ""
  })

  const tagsViewStore = useTagsViewStore()

  const login = async (userInfo: UserLoginData) => {
    try {
      const response = await loginApi(userInfo)
      const { data } = response
      state.token = data.token
      setToken(state.token)
    } catch (error) {
      return Promise.reject(error)
    }
  }

  const logout = () => {
    state.token = ""
    removeToken()
    // 所有信息清空
    tagsViewStore.delAllView()
  }

  return {
    login,
    state,
    logout
  }
})
